<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script th:inline="javascript">
	var mode = [(${mode})];
	[# th:if="${mode == 0}"]
		// 组装filter中会用到的字段值
		function getCondFieldsValue(condFieldArr) {
			console.log('getCondFieldsValue condFieldArr', condFieldArr, 'length', Object.keys(condFieldArr).length);
			if (Object.keys(condFieldArr).length === 0) {
				return {};
			}
			var json = {};
			for (var k in condFieldArr) {
				var fName = condFieldArr[k].fieldName;
				if (findObj(fName)) {
					json[fName] = findObj(fName).value;
				} else {
					console.error("Cond field " + fName + " is not exist in ModuleFieldSelectCtl's filter")
				}
			}
			return json;
		}

		function bindCondFieldsChangeEvent(condFieldArr, formName, ctlFieldName, formCode, defaultOptVal, parentId) {
			console.log('bindCondFieldsChangeEvent condFieldArr', condFieldArr);
			if (Object.keys(condFieldArr).length === 0) {
				return;
			}
			for (var k in condFieldArr) {
				var fName = condFieldArr[k].fieldName;
				console.log('bindCondFieldsChangeEvent fName', fName);
				$(fo(fName, formName)).on("change",function(){
					console.log('bindCondFieldsChangeEvent change', fName);
					onCondFieldChange(condFieldArr, formName, ctlFieldName, formCode, defaultOptVal, parentId);
				});
			}
		}

		function onCondFieldChange(condFieldArr, formName, ctlFieldName, formCode, defaultOptVal, parentId) {
			var data = getCondFieldsValue(condFieldArr);
			data['formCode'] = formCode;
			data['fieldName'] = ctlFieldName;
			data['parentId'] = parentId;
			ajaxPost('/flow/macro/getModuleFieldCtlOptions', data).then((data) => {
				console.log('data', data);
				if (data.code == 200) {
					$(fo(ctlFieldName, formName)).html('<option value=""></option>' + data.data.options);
					var deOptVal = defaultOptVal.split(",");
					console.log('onCondFieldChange defaultOptVal', defaultOptVal, 'deOptVal', deOptVal);
					$(fo(ctlFieldName, formName)).val(deOptVal).trigger('change');
				} else {
					myMsg(data.msg, 'error');
				}
			});
		}

		function initModuleFieldCtl(fieldName, formName, defaultOptVal, defaultOptText, isReadonly, pageType, isAjax, canManualInput, isMulti,
									isSimilar, formCode, flowId, isRealTime, condFieldArr, nestTableRowId, isPageShow, isNeedMap, canOpenWinSel, nestFieldName, parentId) {
			if (isPageShow) {
				return;
			}

			var ctlFieldName = fieldName;
			if (nestTableRowId != -1) {
				ctlFieldName = 'nest_field_' + nestFieldName + '_' + ctlFieldName + '_' + nestTableRowId;
			}
			console.log("findObj(" + ctlFieldName + ")", findObj(ctlFieldName));
			if (findObj(ctlFieldName) && findObj(ctlFieldName).tagName == 'SELECT') {
				if (!isAjax) {
					var ops = {
						// tokenSeparators: "\\,", // 使用转义的逗号作为分隔符，此属性无法解决值中带有逗号，致无法显示的问题
					};
					// 如果是在嵌套表格中需对样式加以调式，否则 initTr 方法会将宽度置为 99%
					if (nestTableRowId != -1) {
						if (canOpenWinSel) {
							opts['width'] = '80%';
						}
					}
					$sel2 = $(findObj(ctlFieldName)).select2(opts);

					// 根据条件取得表单域宏控件下拉框中的选项
					onCondFieldChange(condFieldArr, formName, ctlFieldName, formCode, defaultOptVal, parentId);

					// 绑定事件，当条件中的字段变化时，重新请求
					bindCondFieldsChangeEvent(condFieldArr, formName, ctlFieldName, formCode, defaultOptVal);
				}
				else {
					var opts = {
						tags: canManualInput,	// 允许手动添加
						multiple: isMulti,
						// tokenSeparators: "\\,", // 使用转义的逗号作为分隔符，此属性无法解决值中带有逗号，致无法显示的问题
						placeholder: '请输入关键词',	// 默认文字提示
						language: 'zh-CN',
						escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
						minimumInputLength: isSimilar ? 2 : isMulti ? 0 : 1,
						ajax: {
							url: "/flow/macro/getAjaxOptions.do?fieldName=" + fieldName + "&formCode=" + formCode + "&flowId=" + flowId,
							dataType: 'json',
							delay: 250,
							data: function (params) {
								var d = getCondFieldsValue(condFieldArr);
								d["q"] = params.term;
								return d;
							},
							cache: false,
							processResults: function (data, params) {
								return {
									results: data
								};
							}
						},

						templateResult: function formatRepo(repo){return repo.text},
						templateSelection: function formatRepoSelection(repo){return repo.text}
					};
					// 如果是在嵌套表格中需对样式加以调式，否则 initTr 方法会将宽度置为 99%
					if (nestTableRowId != -1) {
						if (canOpenWinSel) {
							opts['width'] = '80%';
						}
					}
					$sel2 = $(findObj(ctlFieldName)).select2(opts);
				}
			}

			if (isAjax && defaultOptText != '') {
				var deOptVal = defaultOptVal.split(",");
				var deOptText = defaultOptText.split(",");
				// $("#" + fieldName + ).val(deOptVal).trigger('change'); // 对于ajax型的无效
				for (var i=0; i < deOptVal.length; i++) {
					var option = new Option(deOptText[i], deOptVal[i], true, true);
					$(findObj(ctlFieldName)).append(option).trigger('change');
				}
			}

			if (defaultOptText != '') {
				if (isRealTime) {
					console.log('do onSelect');
					// 根据request传入的值实时进行映射
					onSelect(fieldName, formName, defaultOptVal, defaultOptText, isPageShow, nestTableRowId, isNeedMap, pageType, formCode, flowId, condFieldArr, nestFieldName);
				}
			}

			console.log('ctlFieldName', fo(ctlFieldName, formName), fo(ctlFieldName, formName).tagName);
			if (fo(ctlFieldName, formName) && fo(ctlFieldName, formName).tagName=='SELECT') {
				$(fo(ctlFieldName, formName)).on("select2:select", function (e) {
					var id = '';
					var text = '';
					// 当 e.params不存在时，是因为启用了选择按钮，在selByModuleListSel中触发了该事件
					if (e.params) {
						id = e.params.data.id;
						text = e.params.data.text;
					} else {
						id = $(this).val();
						text = $(findObj(ctlFieldName)).find("option:selected").text();
					}

					if (isReadonly) {
						// 如果是只读模式，则因为select2新版中没有只读模式，所以此处强制恢复为request传过来的默认值
						if (defaultOptVal != "") {
							if (id != defaultOptVal) {
								$(findObj(ctlFieldName)).html('<option value="' + defaultOptVal + '">' + defaultOptText + '</option>');
								return;
							}
						}
					}

					onSelect(fieldName, formName, id, text, isPageShow, nestTableRowId, isNeedMap, pageType, formCode, flowId, condFieldArr, nestFieldName);
				});
			}
		}

		initModuleFieldCtl('[(${fieldName})]', '[(${formName})]', '[(${defaultOptVal})]', '[(${defaultOptText})]', [(${isReadonly})], '[(${pageType})]', [(${isAjax})],
				[(${canManualInput})], [(${isMulti})], [(${isSimilar})], '[(${formCode})]', [(${flowId})], [(${isRealTime})], [(${condFieldArr})], [(${nestTableRowId})], [(${isPageShow})], [(${isNeedMap})], [(${canOpenWinSel})], '[(${nestFieldName})]', [(${parentId})]);
	[/]
	[# th:if="${mode != 0}"]
		// 根据控件属性中requestParam传入的值实时进行映射
		[# th:if="${defaultOptText != '' && editable}"]
			console.log('real time onSelect');
			onSelect('[(${fieldName})]', '[(${formName})]', "[(${defaultOptVal})]", "[(${defaultOptText})]", [(${isPageShow})],
					[(${nestTableRowId})], [(${isNeedMap})], '[(${pageType})]', '[(${formCode})]', [(${flowId})], [(${condFieldArr})], '[(${nestFieldName})]');
		[/]

		// 侦听宏控件的值有没有发生变化，如果值发生改变，需进行映射，另外控件自身为被另一个表单域选择宏控件映射的字段改变时，也需重新映射
		function addChangeListener(fieldName, formName, nestTableRowId, isPageShow, isNeedMap, pageType, formCode, flowId, condFieldArr, nestFieldName) {
			if (isPageShow) {
				return;
			}
			var ctlFieldName = fieldName;
			if (nestTableRowId != -1) {
				ctlFieldName = 'nest_field_' + nestFieldName + '_' + ctlFieldName + '_' + nestTableRowId;
			}
			var obj = findObj(ctlFieldName, formName);
			if (!obj) {
				console.warn('字段' + ctlFieldName + '不存在，注意：嵌套表格宏控件中不支持检测变化');
				return;
			}
			var oldValue = obj.value;
			var curFormId = formName;

			console.log('ctlFieldName', ctlFieldName, 'oldValue', oldValue);
			var sint = setInterval(function(){
				// 在嵌套表格宏控件中字段名称会被改写，故此处需检测是否存在
				// 当被缓存时，切换选项卡，o(curFormId)会为null，故不能判断其为null时就清除interval，否则切换回时就无法响应了，
				// 而当点击刷新按钮后，ctlObj会变为null，此时可以清除interval
				if (o(curFormId)) {
					var ctlObj = fo(ctlFieldName, curFormId);
					// 右上角点击刷新按钮，刷新流程的时候，会出现fo(ctlFieldName, curFormId)为null的情况
					// 应该是此时curFormId存在，而内容却被清掉了所致，因为此时刷新后的内容还没有被赋予到form里面
					if (!ctlObj) {
						console.warn('ModuleFieldSelectCtl Field: clearInterval for form ' + ctlFieldName + ' is not found.');
						window.clearInterval(sint);
						return;
					}
					var val = ctlObj.value;
					if (val && oldValue != val) {
						console.log("formName=" + formName + " newValue=" + val + " oldValue=" + oldValue);
						if (val != "") {
							var text = fo(ctlFieldName + "_realshow", curFormId).value;
							console.log("onSelect: id=" + val + " text=" + text);
							onSelect(fieldName, formName, val, text, isPageShow, nestTableRowId, isNeedMap, pageType, formCode, flowId, condFieldArr, '[(${nestFieldName})]');
						}
						oldValue = val;
					}
				}
			},100);
			// 当菜单项不启用缓存时，只能通过如下方法才能清除interval
			getCurFormUtil().addInterval(sint, formName);
		}

		console.log('macro_module_field_select_ctl_js check val');
		addChangeListener("[(${fieldName})]", "[(${formName})]", "[(${nestTableRowId})]", [(${isPageShow})], [(${isNeedMap})], '[(${pageType})]', '[(${formCode})]', [(${flowId})], [(${condFieldArr})], '[(${nestFieldName})]');
	[/]

	var curModuleFieldName = "";
	if (typeof moduleFieldMap === 'undefined') {
		// 只创建1次
		moduleFieldMap = new MyMap();
	}

	function getModuleFieldMap(moduleFieldName) {
		var json = moduleFieldMap.get(moduleFieldName);
		if (!json) {
			var map = new MyMap();
			moduleFieldMap.put(moduleFieldName, map);
			return map;
		} else {
			return json.value;
		}
		/*console.log('getModuleFieldMap moduleFieldName', moduleFieldName);
        console.log('getModuleFieldMap moduleFieldMap', moduleFieldMap);
        console.log('getModuleFieldMap map', map);
        return map;*/
	}

	function clearModuleFieldMap(moduleFieldName) {
		if (moduleFieldMap.containsKey(moduleFieldName)) {
			moduleFieldMap.remove(moduleFieldName);
		}
	}

	function putModuleFieldValue(moduleFieldName, fieldName, value) {
		getModuleFieldMap(moduleFieldName).put(fieldName, value);
	}

	function getModuleFieldMappedValue(fieldName) {
		if (curModuleFieldName !== '') {
			var map = getModuleFieldMap(curModuleFieldName);
			// console.log('curModuleFieldName', curModuleFieldName, 'map', map);
			if (map.containsKey(fieldName)) {
				return map.get(fieldName).value;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	// 选择后重新映射
	function onSelect(fieldName, formName, id, text, isPageShow, nestTableRowId, isNeedMap, pageType, formCode, flowId, condFieldArr, nestFieldName) {
		console.log('onSelect', fieldName, id, eventTarget);

		// 延迟0.2秒，否则onModuleFieldChange事件中通过fo取值时，有时会因为选择抽屉退出慢，fo用的为抽屉的formName，导致可能取不到
		// 当然也可以用event.id来获取change后的值，但得考虑到有可能用fo来取其它字段的值
		// 如: fo('xmbh').value,
		setTimeout(function() {
			eventTarget.fireEvent({
				type: EVENT_TYPE.MODULE_FIELD_SEL,
				flowId: flowId,
				id: id,
				text: text,
				fieldName: fieldName,
				formCode: formCode,
				formName: formName
			});
		}, 200);

		// 触发change事件，以使得其它依赖于此控件的表单域选择控件能够与之联动
		$(fo(fieldName)).trigger('change');

		if (!isNeedMap) {
			return;
		}

		var formObj = o(formName);
		// 此处需传openerFormCode，否则点击被映射得到的其它表单域选择宏控件的放大镜时，弹出module_list_sel.jsp时会报错：openerFormCode不能为空
		// 因为convertToHTML时，会从request中获取openerFormCode，当点击放大镜时，传入module_list_sel.jsp
		var ajaxData = {
			fieldName: fieldName,
			formCode: formCode,
			openerFormCode: formCode,
			flowId: flowId,
			id: id,
			text: text,
			pageType: pageType,
			nestTableRowId: nestTableRowId,
			nestFieldName: nestFieldName
		}

		for (var k in condFieldArr) {
			var fName = condFieldArr[k].fieldName;
			if (isPageShow) {
				ajaxData[fName] = condFieldArr[k].fieldValue;
			} else {
				var obj = findObj(fName, formName);
				var objVal = '';
				if (obj) {
					if (obj.tagName=='RADIO') {
						objVal = getRadioValue(fName);
					}
					else if (obj.tagName == "CHECKBOX") {
						objVal = getCheckboxValue(fName);
					}
					else {
						objVal = obj.value;
					}
				}
				// console.log(fName + '=' + objVal);
				ajaxData[fName] = objVal;
			}
		}

		ajaxPost('/flow/macro/onFieldCtlSelect', ajaxData).then((data) => {
			console.log('onFieldCtlSelect start ' +  fieldName);
			console.log(data);

			curModuleFieldName = fieldName;
			var data = data.data;
			if (isPageShow) {
				for(var i=0, l=data.length; i < l; i++) {
					var json = data[i];
					// 不替换本表单域选择宏控件
					if (json.fieldName != fieldName) {
						var curFieldName = json.fieldName;
						if (nestTableRowId != -1) {
							curFieldName = 'nest_field_' + nestFieldName + '_' + curFieldName + '_' + nestTableRowId;
						}
						var obj = findObjInFormObj(formObj, curFieldName);
						if (obj) {
							if (obj.tagName == 'SPAN') {
								$(obj).html(json.setValue);
							} else {
								if (obj.tagName == 'INPUT' && obj.getAttribute("type") == 'file') {
									console.warn('文件宏控件 ' + obj.getAttribute('title') + ' ' + obj.name + ' 的值不能直接被映射');
								} else {
									$(obj).val(json.value);
								}
							}
						}
						// 当字段不可写时
						var objShow = findObjInFormObj(formObj, curFieldName + "_show");
						if (objShow == null) {
							// 宏控件的显示值
							objShow = findObjInFormObj(formObj, curFieldName + "_realshow");
						}
						if (objShow) {
							$(objShow).html(json.setValue);
						}
					}
				}
			}
			else {
				clearModuleFieldMap(fieldName);

				for(var i=0, l = data.length; i < l; i++) {
					var json = data[i];
					var curFieldName = json.fieldName;
					if (nestTableRowId != -1) {
						curFieldName = 'nest_field_' + nestFieldName + '_' + curFieldName + '_' + nestTableRowId;
					}
					var obj = findObjInFormObj(formObj, curFieldName);
					if (!obj) {
						console.warn("onSelect 映射字段 " + curFieldName + " 不存在");
						continue;
					}

					// 不替换本表单域选择宏控件
					if (json.fieldName != fieldName) {
						putModuleFieldValue(fieldName, curFieldName, json.value);

						if (json.isMacro) {
							// 清除realname
							var objRealName = findObjInFormObj(formObj, curFieldName + "_realname");
							if (objRealName) {
								$(objRealName).remove();
							}
							// 清除文件宏控件中的文件链接
							// $('#helper_' + json.fieldName).remove();
							$(formObj).find('#helper_' + curFieldName).remove();

							// replaceValue(json.fieldName, json.setValue, json.value, json.checkJs, json.macroType);
							replaceValueByFormObj(curFieldName, json.setValue, json.value, json.checkJs, json.macroType, formObj);
							console.log('curFieldName', curFieldName, 'json.setValue', json.setValue);

							// 20240318 如果是sql宏控件，则通过onSQLCtlRelateFieldChange生成
							if (json.macroType == 'macro_sql') {
								try {
									eval('onSQLCtlRelateFieldChange_[(${formName})]_' + curFieldName + '()');
								} catch (e) {
									console.log(e);
								}
							}

							initFormCtl('[(${formName})]');
						} else {
							if (obj.type == "radio") {
								// setRadioValue(json.fieldName, json.setValue);
								setRadioValueByFormObj(formObj, curFieldName, json.setValue);
								$(obj).trigger('change');
							}
							else if (obj.type == 'checkbox') {
								if (json.setValue == '1') {
									$(obj).prop('checked', true);
								} else {
									$(obj).prop('checked', false);
								}
								$(obj).trigger('change');
							}
							else {
								// var obj = findObj(json.fieldName, formName);
								// if (obj) {
								if (obj.tagName != 'SPAN') {
									if (obj.tagName == "SELECT") {
										$(obj).val(json.setValue);
									} else {
										$(obj).val(json.value);
									}

									$(obj).trigger('change');
								}
								else {
									// 不可写字段
									$(obj).html(json.setValue);
								}
								// }
								// var objShow = findObj(json.fieldName + "_show", formName);
								var objShow = findObjInFormObj(formObj, curFieldName + "_show");
								if (objShow) {
									$(objShow).html(json.setValue);
								}
							}
						}
					}
				}
			}

			// 选择后应用显示规则
			var isDoViewJS = true;
			try {
				isDoViewJS = isDoViewJSOnModuleListSel();
			} catch (e) {
				console.warn(e);
			}
			if (isDoViewJS) {
				try {
					console.log(typeof(doViewJS_[(${formName})])); // 打印出来是function
					console.log(doViewJS_[(${formName})]);	// 打印出来是方法体
					// 直接调用不生效，须 eval
					// doViewJS();
					// 调用显示规则
					eval('doViewJS_[(${formName})]()');
				} catch (e) {
					console.warn(e);
				}
			}

			try {
				// 调用事件 onModuleFieldSelected，如开工中调用：initXmzt()
				onModuleFieldSelected(curModuleFieldName);
			} catch (e) {
				console.warn(e);
			}

			console.log('onFieldCtlSelect end ' + fieldName + ' isDoViewJS=' + isDoViewJS);
		});
	}
</script>
</body>
</html>